package com.hclc.config;

import com.baomidou.mybatisplus.core.enums.IEnum;
import com.google.common.collect.Maps;
import org.springframework.core.convert.converter.Converter;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 枚举编码 -> 枚举 转化器
 *
 * @ClassName IntegerToEnumConverter
 * @Author: yurj
 * @Mail：1638234804@qq.com
 * @Date: Create in 15:45 2020/11/12
 * @version: 1.0
 */
public class IntegerToEnumConverter<T extends IEnum> implements Converter<Integer, T> {
    /**
     * 枚举map
     */
    private Map<Integer, T> enumMap = Maps.newHashMap();

    /**
     * 将枚举存储到map
     *
     * @param enumType
     * @return
     * @author yurj
     * @version 1.0
     * @date 2020/11/12 16:15
     */
    public IntegerToEnumConverter(Class<T> enumType) {
        T[] enums = enumType.getEnumConstants();
        Stream.of(enums).forEach(s -> {
            enumMap.put(Integer.valueOf(String.valueOf(s.getValue())), s);
        });
    }

    /**
     * 根据code获取枚举
     *
     * @param source
     * @return T
     * @author yurj
     * @version 1.0
     * @date 2020/11/12 16:16
     */
    @Override
    public T convert(Integer source) {
        T t = enumMap.get(source);
        if (Objects.isNull(t)) {
            throw new IllegalArgumentException("无法匹配对应的枚举类型");
        }
        return t;
    }
}
